package com.yangke.springcloud.controller;

import com.yangke.springcloud.entites.CommonResult;
import com.yangke.springcloud.entites.Payment;
import com.yangke.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 向数据库中添加支付对象
     * @param payment
     * @return
     */
    @PostMapping(value = "/payment/create")
    public CommonResult addPayment(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("添加数据："+payment);
        if(result>0){
            return new CommonResult(200,"数据添加成功,serverPort"+serverPort,payment);
        }else{
            return new CommonResult(444,"数据添加失败,serverPort"+serverPort,null);
        }
    }


    /**
     * 通过id查询数据库中的支付对象
     * @param id
     * @return
     */
    @GetMapping(value = "/payment/getPayment/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentByid(id);
        log.info("查询结果："+payment);
        if(payment!=null){
            return new CommonResult(200,"数据查询成功，结果为："+payment+",serverPort"+serverPort,payment);
        }else {
            return new CommonResult(444,"数据查询失败,serverPort"+serverPort,null);

        }
    }

    /**
     * 服务发现Discovery
     */
    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("element:"+service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"
                    +instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri());
        }

        return this.discoveryClient;
    }

    /**
     * 负载均衡测试
     * @return
     */
    @GetMapping(value = "/payment/lb")
    public String lb(){
        // 返回服务接口
        return serverPort;
    }

}